<script setup>
import { reactive, onBeforeMount, ref } from 'vue'
import { to } from 'sf-utils2'
import { ElMessage } from 'element-plus'
import SvgIcon from '@/components/svg-icon/index.vue'
import loginApi from '@/api/modules/user-center/login'
import { encrypt } from '@/utils/jsencrypt'
import useUserStore from '@/store/use-user-store'
import useRouterPlus from '@/router/use-router-plus'
import profile from '@root/profile'

const userStore = useUserStore()
const { router } = useRouterPlus()
const initial = ref(false)
const formProps = reactive({
  /**
   * 表单实例
   * @type {FormInstance}
   */
  instanceRef: null,
  /**
   * 表单数据
   */
  model: {},

  /**
   * 表单验证规则
   */
  rules: {
    username: [{ required: true, message: '请输入账号', trigger: 'change' }],
    password: [{ required: true, message: '请输入密码', trigger: 'change' }],
    code: [{ required: true, message: '请输入验证码', trigger: 'change' }]
  },

  loading: false
})

/**
 * 表单验证规则
 */
async function onSubmit() {
  const [valid, errorFields] = await to(formProps.instanceRef.validate())
  if (!valid) {
    // 校验不通过，提示文字
    const first = Object.values(errorFields).flat().shift()
    return ElMessage.error({
      message: first?.message,
      duration: 5000
    })
  }

  formProps.loading = true
  // 密码登录
  const reqData = {
    mobile: formProps.model?.username,
    password: encrypt(formProps.model?.password),
    loginType: 'PASSWORD'
  }
  const [res, err] = await to(loginApi.login(reqData))
  formProps.loading = false
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))

  ElMessage.success('登录成功')
  userStore.token = res?.data?.token
  router.push('/home')
  // 校验通过，提交表单
  console.log('提交表单', formProps.model)
}

onBeforeMount(() => {
  if (['dev', 'sit', 'uat', 'prd'].includes(profile.APP_MODE)) {
    // 如果是sit环境，跳转到新核心的登录页面
    return (window.location.href = profile.newCoreAddress + '/login?systemId=cf-manage')
  }
  initial.value = true
})
</script>

<template>
  <main
    v-if="initial"
    class="page"
  >
    <article class="page__banner hidden min-w-[576px] px-14 py-12 lg:block">
      <img
        src="@/assets/imgs/login/zslogo.svg"
        alt="浙商logo"
        class="h-[26px] w-[122px]"
      >
    </article>

    <article class="flex flex-1 flex-col items-center justify-center bg-white">
      <!--标题-->
      <header
        class="flex gap-4 text-[28px] font-medium leading-9"
        aria-label="title"
      >
        <h1 id="title">
          消金业务综合平台
        </h1>
        <span class="self-center rounded bg-orange-50 px-[10px] py-1 text-base text-orange"> 资管端 </span>
      </header>

      <!--表单-->
      <el-form
        :ref="(el) => (formProps.instanceRef = el)"
        class="mt-10 flex w-[336px] flex-col"
        :model="formProps.model"
        :show-message="false"
        :rules="formProps.rules"
        @keydown.enter="onSubmit"
      >
        <!--账号-->
        <el-form-item
          prop="username"
          required
        >
          <el-input
            v-model.trim="formProps.model.username"
            type="text"
            class="h-12 w-full"
            placeholder="账号"
            aria-label="账号"
            name="username"
            autocomplete="username"
            clearable
          >
            <template #prefix>
              <SvgIcon
                svg="login/account"
                size="16"
              />
            </template>
          </el-input>
        </el-form-item>

        <!--密码-->
        <el-form-item
          prop="password"
          required
        >
          <el-input
            v-model.trim="formProps.model.password"
            type="password"
            class="h-12 w-full"
            placeholder="密码"
            aria-label="账号"
            autocomplete="current-password"
            clearable
            show-password
          >
            <template #prefix>
              <SvgIcon
                svg="login/password"
                size="16"
              />
            </template>
          </el-input>
        </el-form-item>

        <!--验证码-->
        <el-form-item
          v-if="false"
          prop="code"
        >
          <el-input
            v-model="formProps.model.code"
            type="text"
            class="w-50 h-12"
            placeholder="验证码"
            aria-label="验证码"
            autocomplete="one-time-code"
          >
            <template #prefix>
              <SvgIcon
                svg="login/verify"
                size="16"
              />
            </template>
          </el-input>

          <div
            v-if="false"
            class="w-30 ml-4 h-full rounded bg-primary-50 text-center text-base font-bold leading-10 text-primary"
          >
            3 * 4 = ?
          </div>
        </el-form-item>

        <!--记住密码-->
        <el-form-item
          v-if="false"
          prop="remember"
        >
          <el-checkbox v-model="formProps.model.remember">
            记住密码
          </el-checkbox>
        </el-form-item>

        <el-button
          class="h-12 w-full text-base"
          type="primary"
          :loading="formProps.loading"
          @click="onSubmit"
        >
          登 录
        </el-button>
      </el-form>
    </article>
  </main>
</template>

<style scoped lang="less">
.page {
  inline-size: 100vw;
  block-size: 100vh;
  display: flex;
}

.page__banner {
  inline-size: 40%;
  background-image: url('@/assets/imgs/login/background.svg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

// ---------------------------设置输入框图标颜色-------------------------------
.ijep-form-item :deep(.ijep-input__prefix-inner) {
  transition: color 0.3s;
}

// 设置输入框图标颜色 选中状态颜色
.ijep-form-item:focus-within :deep(.ijep-input__prefix-inner) {
  color: var(--tzx-primary-color);
}

// 设置输入框图标颜色 错误状态颜色
.ijep-form-item.is-error :deep(.ijep-input__prefix-inner) {
  color: var(--tzx-error-color);
}

// --------------------autocomplete------------------------------------
:deep(.ijep-input__wrapper):has(:-webkit-autofill, :autofill) {
  // 自动填充背景色
  background-color: var(--tzx-primary-color-50);
}
</style>
